﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using WcfServiceShared;

namespace WcfServiceLibrary1
{
    public class Service : IService
    {

        //This should work just fine, as its a standard WCF service call that
        //works just fine, beacuse we have adoned the WCF service interface
        //with the ReferencePreservingDataContractFormatAttribute to 
        //allow circular references
        public List<Person> GetPeople()
        {
            Person father = new Person { Age = 42, Name = "brad", Parent = null };
            father.Children = CreateChildren(father);
            Person mum = new Person { Age = 40, Name = "pam", Parent = null };
            mum.Children = CreateChildren(mum);

            List<Person> people = new List<Person>();
            people.Add(father);
            people.Add(mum);
            return people;
        }


        //We expect this to fail as this the proxy method call,
        //is calling a WCF service method that has the default 
        //DataContractSerializer which CAN'T deal with circular
        //references
        public List<Person> GetPeopleWithOutCicularReferencing()
        {
            Person father = 
                new Person { Age = 42, Name = "brad", Parent = null };
            father.Children = CreateChildren(father);
            Person mum = 
                new Person { Age = 40, Name = "pam", Parent = null };
            mum.Children = CreateChildren(mum);

            List<Person> people = new List<Person>();
            people.Add(father);
            people.Add(mum);
            return people;
        }


        private List<Person> CreateChildren(Person parent)
        {
            List<Person> children = new List<Person>();
            children.Add(new Person { Age = 15, Name = "sam", 
                Parent = parent, Children = null });
            children.Add(new Person { Age = 20, Name = "greta", 
                Parent = parent, Children = null });
            return children;
        }

    }
}
